//https://blog.csdn.net/ngl272/article/details/87887885
//https://blog.csdn.net/klandor2008/article/details/85062687
var mqtt = require('../../mqtt/mqtt.min.js')
const crypto = require('../../mqtt/hex_hmac_sha1.js');
// index.js
Page({
  data: {
    videoUrl: '', // 视频地址
    logs: [], // 操作日志
    client: null,
  },

  onLoad: function() {
    this.doConnect()
  },

  doConnect() {
    const deviceConfig = {
      productKey: "a1CpqqlEPyi",
      deviceName: "BCRV2401022024080100002",
      deviceSecret: "88ae6dc8c26f86bee7df672142944e73",
      regionId: "cn-shanghai"
    };
    const options = this.initMqttOptions(deviceConfig);
    console.log(options)
    this.client = mqtt.connect('wxs://a1CpqqlEPyi.iot-as-mqtt.cn-shanghai.aliyuncs.com', options)
    this.client.on('connect', () => {// 使用箭头函数保留this上下文
      console.log("connect to server pass")
      this.client.subscribe('/a1CpqqlEPyi/BCRV2401022024080100002/user/cmd/update_params', (err) => {
        if (!err) {
          console.log("subscribe pass")
          // 可以在这里更新logs
          this.setData({
            logs: [...this.data.logs, '订阅成功']
          })
        }
      })
    })
    this.client.on('message', function (topic, message) {
      let msg = message.toString();
      console.log('recv msg: ' + msg)
    })
  },

  initMqttOptions(deviceConfig) {
    const params = {
      productKey: deviceConfig.productKey,
      deviceName: deviceConfig.deviceName,
      timestamp: Date.now(),
      clientId: Math.random().toString(36).substr(2),
    }
    //CONNECT参数
    const options = {
      keepalive: 60, //60s
      clean: true, //cleanSession不保持持久会话
      protocolVersion: 4 //MQTT v3.1.1
    }
    //1.生成clientId，username，password
    options.password = this.signHmacSha1(params, deviceConfig.deviceSecret);
    options.clientId = `${params.clientId}|securemode=2,signmethod=hmacsha1,timestamp=${params.timestamp}|`;
    options.username = `${params.deviceName}&${params.productKey}`;

    return options;
  },
  /*
  生成基于HmacSha1的password
  参考文档：https://help.aliyun.com/document_detail/73742.html?#h2-url-1
*/
  signHmacSha1(params, deviceSecret) {

    let keys = Object.keys(params).sort();
    // 按字典序排序
    keys = keys.sort();
    const list = [];
    keys.map((key) => {
      list.push(`${key}${params[key]}`);
    });
    const contentStr = list.join('');
    return crypto.hex_hmac_sha1(deviceSecret, contentStr);
  },

  // 向上移动
  moveUp() {
    const timestamp = new Date().toLocaleTimeString();
    const log = `[${timestamp}] 向上移动`;
    this.addLog(log);
    console.log(log);
  },

  // 向下移动
  moveDown() {
    const timestamp = new Date().toLocaleTimeString();
    const log = `[${timestamp}] 向下移动`;
    this.addLog(log);
    console.log(log);
  },

  // 向左移动
  moveLeft() {
    const timestamp = new Date().toLocaleTimeString();
    const log = `[${timestamp}] 向左移动`;
    this.addLog(log);
    console.log(log);
  },

  // 向右移动
  moveRight() {
    const timestamp = new Date().toLocaleTimeString();
    const log = `[${timestamp}] 向右移动`;
    this.addLog(log);
    console.log(log);
    this.client.publish("/sys/a1CpqqlEPyi/BCRV2401022024080100002/thing/lan/blacklist/update_reply", "abcdefg",{qos:0});
    // this.sendCommand("right");
  },
  
  // 发送控制命令到API
  sendCommand(direction) {
    const timestamp = new Date().toLocaleTimeString();
    this.setData({
      isLoading: true
    });

    // 记录操作日志
    const log = `[${timestamp}] 发送${direction}指令`;
    this.addLog(log);

    // 调用HTTP接口
    wx.request({
      url: 'http://192.168.2.13:8080/test',
      method: 'POST',
      data: {
        action: 'move',
        direction: direction
      },
      success: (res) => {
        const successLog = `[${timestamp}] API响应: ${res.data.message || '成功'}`;
        this.addLog(successLog);
        console.log(`API调用成功: ${direction}`, res);
      },
      fail: (err) => {
        const errorLog = `[${timestamp}] API错误: ${err.errMsg}`;
        this.addLog(errorLog);
        console.error(`API调用失败: ${direction}`, err);
      },
      complete: () => {
        this.setData({
          isLoading: false
        });
      }
    });
  },

  // 添加日志到列表
  addLog(log) {
    const logs = [...this.data.logs, log];
    // 限制日志数量，避免占用过多内存
    if (logs.length > 10) {
      logs.shift();
    }
    this.setData({
      logs
    });
  }
})